package cn.edu.qfnu.common.exception;

import cn.edu.qfnu.common.exception.authen.NotLoginException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Tax Analysis Project part of Web Service
 * Created by LS on 2017/7/13.
 */
public class ExceptionHandler implements HandlerExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                         Object handler, Exception ex) {
        logger.error("捕获到的异常: ", ex);

        String message;

        if (ex instanceof NotLoginException) {
            message = ex.getMessage();
        } else {
            Writer out = new StringWriter();
            PrintWriter sWriter = new PrintWriter(out);
            ex.printStackTrace(sWriter);
            message = out.toString();
        }


        return new ModelAndView("errors", "message", message);
    }
}
